package com.example.test.common.utils;

import com.example.test.common.excetion.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

@Slf4j
public class AESUtil {
	
	private final String sKey = "herbalife1234567";
	private final String ivParameter = "1234567herbalife";
	private static AESUtil instance = null;

	private AESUtil() {}

	public static AESUtil getInstance() {
		if (instance == null) {
            instance = new AESUtil();
        }
		return instance;
	}

	/**
	 * 加密
	 * @param sSrc
	 * @return
	 */
	public String encrypt(String sSrc) {
		String result = "";
		try {
			Cipher cipher = Cipher.getInstance("AES/OFB/NoPadding");
			byte[] raw = sKey.getBytes();
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
			IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
			byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
			result = Base64.encodeBase64String(encrypted);
		} catch (Exception e) {
			log.error("加密异常", e);
			throw new BusinessException("500",e.getMessage());
		}
		return result;

	}

	/**
	 * 解密
	 * @param sSrc
	 * @return
	 */
	public String decrypt(String sSrc) {
		try {
			byte[] raw = sKey.getBytes("ASCII");
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES/OFB/NoPadding");
			IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			byte[] encrypted1 = Base64.decodeBase64(sSrc);
			byte[] original = cipher.doFinal(encrypted1);
			String originalString = new String(original, "UTF-8");
			return originalString;
		} catch (Exception e) {
			log.error("解密异常", e);
			throw new BusinessException("500",e.getMessage());
		}
	}


}
